package com.yyt.elasticsearch.service.impl;

import com.yyt.elasticsearch.service.TransTypeService;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class TransTypeServiceImpl implements TransTypeService {


    @Autowired
    private RestHighLevelClient client;

    private Logger logger = LoggerFactory.getLogger(TransTypeServiceImpl.class);


    /**
     * 查询文档
     */
    @Test
    public List getTransType() throws IOException {

        List transTypeList = null;
        SearchRequest searchRequest = new SearchRequest("book");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("summary","教你"));
        // searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        RestStatus status = searchResponse.status();
        TimeValue took = searchResponse.getTook();
        Boolean terminatedEarly = searchResponse.isTerminatedEarly();
        boolean timedOut = searchResponse.isTimedOut();

        float maxScore = searchResponse.getHits().getMaxScore();
        TotalHits totalHits = searchResponse.getHits().getTotalHits();
        SearchHit[] hits = searchResponse.getHits().getHits();


        for (SearchHit hit : hits) {
            logger.info("id:{}", hit.getId());
            logger.info("索引名:{}", hit.getIndex());
            logger.info("分数:{}", hit.getScore());
            logger.info("source string:{}", hit.getSourceAsString());
            logger.info("source map:{}", hit.getSourceAsMap());
        }

        logger.info("totalHits :{}",totalHits);

        logger.info("maxScore:{}",maxScore);
        logger.info("searchResponse:{}",searchResponse);
        return transTypeList;
    }
}
